import React, {Fragment } from 'react';
import { connect } from 'dva';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Tree,
  Icon,
  Button,
  Dropdown,
  Modal,
  message,
  Divider,
} from 'antd';
import StandardTable from 'components/StandardTable';
import PageHeaderLayout from '../../../layouts/PageHeaderLayout'
import styles from '../TableList.less';
import {arrayToTree,getParentKey,addParams} from './util';

const {TreeNode} = Tree;
const {Search} = Input;
const FormItem = Form.Item;
const {confirm} = Modal;

// 节点弹出框
const TreeForm = Form.create()(props => {
  const { modalVisible, form, handleCommit, handleModalVisible,modalType,modalItem } = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
     const method = (modalType.indexOf('新增')>-1)?'post':'patch';
     fieldsValue = {
        ...fieldsValue,
        // id:modalItem.id||0
      }
      handleCommit(fieldsValue,method);
    });
  };
  if(modalType==="修改本部门"){
    return (
      <Modal
        title={`部门树——${modalType}`}// 编辑 modeltype
        visible={modalVisible}
        onOk={okHandle}
        onCancel={() => handleModalVisible()}
      >
        <Row>
          <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="节点Id">
            {form.getFieldDecorator('id', {
              initialValue: modalItem.pid||0,
            })(<Input  disabled />)}
          </FormItem>
          <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="部门名称">
            {form.getFieldDecorator('name', {
              initialValue: modalItem.pname,
              rules: [{ required: true }],
            })(<Input  placeholder="请输入部门名称" />)}
          </FormItem>
        </Row>
      </Modal>
    )
  };
  return (
    <Modal
      title={`部门树——${modalType}`}// 编辑 modeltype
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
    >
      <Row>
        <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="父节点Id">
          {form.getFieldDecorator('pid', {
            initialValue: modalItem.pid||0,
          })(<Input  disabled />)}
        </FormItem>
        <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="当前节点Id">
          {form.getFieldDecorator('id', {
          initialValue: modalItem.id||0,
          })(<Input  disabled />)}
        </FormItem>
        <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="上级部门名称">
          {form.getFieldDecorator('pname', {
            initialValue: modalItem.pname||"已经是最高级",
          })(<Input disabled />)}
        </FormItem>
        <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="下级部门名称">
          {form.getFieldDecorator('name', {
            initialValue: "",
            rules: [{ required: true }],
          })(<Input  placeholder="请输入下级部门名称" />)}
        </FormItem>
      </Row>
    </Modal>
  );
});



// 成员弹出框
const CreateForm = Form.create()(props => {
  const { modalVisible, form, handleCommit, handleModalVisible,modalType,modalItem } = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      const method = modalType==='新增'?'post':'patch';
      fieldsValue = {
        ...fieldsValue,
        id:modalItem.id||0,
      }
      handleCommit(fieldsValue,method);
    });
  };
  return (
    <Modal
      title={`${modalType}直属成员`}// 编辑 modeltype
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
    >
      <Row>
        <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="姓名">
          {form.getFieldDecorator('name', {
            initialValue: modalItem.name,
            rules: [{ required: true }],
          })(<Input placeholder="请输入" />)}
        </FormItem>
      </Row>
      <Row>
        <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="职务">
          {form.getFieldDecorator('job', {
            initialValue: modalItem.job,
            rules: [{ required: true }],
          })(<Input placeholder="请输入" />)}
        </FormItem>
      </Row>
      <Row>
        <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="联系电话">
          {form.getFieldDecorator('tel', {
            initialValue: modalItem.tel,
            rules: [{ required: true }],
          })(<Input placeholder="请输入" />)}
        </FormItem>
      </Row>
      <Row>
        <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="备注">
          {form.getFieldDecorator('memo', {
            initialValue: modalItem.memo,
            rules: [{ required: true }],
          })(<Input placeholder="请输入" />)}
        </FormItem>
      </Row>
    </Modal>
  );
});
@connect(({ sysdepart, loading }) => ({
  sysdepart,
  loading: loading.models.sysdepart,
}))
@Form.create()
export default class Department extends React.Component {
  state = {
    modalVisible: false,// 默认是右侧弹出框
    treeModalVisible:false,
    treeModalType:'新增',
    treeModalItem:{},// 树结点的信息 pid、id、name
    selectedRows: [],
    modalType:'新增',// 编辑还是删除
    modalItem:{}, // 当前编辑行的值
    expandedKeys: [],
    searchValue: '',
    autoExpandParent: true,
    dataList:[],// 待标题的扁平化数组
    treeData:[],// 扁平转换后->树状
    treeId:null,// 记录点击的左侧树状节点的id
    buttonVisible:false,
  };

  componentDidMount(){
    const { dispatch } = this.props;
    dispatch({
      type: 'sysdepart/fetchTree',
    });
  }

  // 初始化props
  componentWillReceiveProps(nextProps){
    const {sysdepart:{data}} = nextProps;
    const {list} = data;
    this.setState({
      treeData:arrayToTree(list),
      dataList:addParams(list),
    })
  }
  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'sysdepart/clear',
    });
  }

  onExpand = (expandedKeys) => {
    this.setState({
      expandedKeys,
      autoExpandParent: false,
    });
  }
  onChange = (e) => {
    const {dataList,treeData} = this.state;
    const {value} = e.target;
    const expandedKeys = dataList.map((item) => {
      if (item.title.indexOf(value) > -1) {
        return getParentKey(item.key,treeData);
      }
      return null;
    }).filter((item, i, self) => item && self.indexOf(item) === i);

    this.setState({
      expandedKeys,
      searchValue: value,
      autoExpandParent: true,
    });
  }

  onDrop=(e)=>{
    // 获取拖拽元素的id、 目标元素的id(注可能是元素上 和 元素与元素之间)
    // 拖拽逻辑： 将目标元素的id置为该元素的pid。
    const dropKey = e.node.props.eventKey;
    const dragKey = e.dragNode.props.eventKey;
    this.props.dispatch({
      type: 'sysdepart/postTree',
      payload:{
        data:{
          id:dragKey,
          pid:dropKey,
        },
        method:'patch',
      },
    })
    message.success("拖拽修改成功");
  }

  handleTreeClick = (keys,e) =>{
    const {eventKey,title:{props}} = e.node.props;
    const name  = props.children[2];
    this.setState({
      treeId:keys[0],
      buttonVisible:true,
      treeModalItem:{
        pid:eventKey,
        id:0,
        pname:name,
      },
    })

    this.props.dispatch({
      type: 'sysdepart/fetchPerson',
      payload:{id:keys[0]},
    })
  }


  handleToModal = (record,type) =>{
    // 如果没有选中树节点 拒绝操作
    if(!this.state.treeId){
      message.error('请在左栏选择具体操作的部门');
      return;
    }
    this.setState({
      modalVisible: true,
      modalItem: record,
      modalType:type,
    });
  };

  handleTreeToModal = (record,type)=>{
    this.setState({
      treeModalVisible: true,
      treeModalItem: record,
      treeModalType:type,
    });
  };

  // 向后端发送增删改请求
  handleCommit = (fields,method) => {
    const {treeId} = this.state;
    this.props.dispatch({
      type: 'sysdepart/postPerson',
      payload: {
        data:{
          ...fields,
        },
        pid:treeId,
        method,
      },
    });
    message.success(`${method}成功`);
    this.setState({
      modalVisible: false,
    });
  };
  handleTreeCommit = (fields,method) => {
    this.props.dispatch({
      type: 'sysdepart/postTree',
      payload: {
        data:{
          ...fields,
        },
        method,
      },
    });
    message.success(`${method}成功`);
    this.setState({
      treeModalVisible: false,
    });
  };
  handleToDel = (record) =>{
    const self = this;
    confirm({
      title: '确定删除该成员吗？',
      content: '一旦删除无法撤回',
      okText: '确认',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        self.handleCommit(record,'delete')
      },
    });
  }

  handleTreeToDel = () =>{
    const self = this;
    const {treeModalItem} =  this.state;
    const record = {
      id:treeModalItem.pid,
    };
    confirm({
      title: `确定删除该部门——${treeModalItem.pname}吗?`,
      content: '删除之后其下子部门均会消失且操作无法撤回！！',
      okText: '确认',
      okType: 'danger',
      cancelText: '取消',
      onOk() {self.handleTreeCommit(record,'delete')}
    });
  };
  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
    });
  };

  handleTreeModalVisible = flag => {
    this.setState({
      treeModalVisible: !!flag,
    });
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };


  render() {
    const columns =
    [
      {
        title: '姓名',
        dataIndex: 'name',
      },
      {
        title: '职务',
        dataIndex: 'job',
      },
      {
        title: '联系电话',
        dataIndex: 'tel',
      },
      {
        title: '备注',
        dataIndex: 'memo',
      },
      {
        title: '操作',
        render: (text,record) => (
          <Fragment>
            <a onClick={()=>this.handleToModal(record,'编辑')}>修改信息</a>
            <Divider type="vertical" />
            <a onClick={()=>this.handleToDel(record)}>删除成员</a>
          </Fragment>
        ),
      },
    ]


    const {sysdepart:{personData},loading}  = this.props;
    const { selectedRows, modalVisible,modalType,modalItem } = this.state;
    const { treeModalVisible,treeModalType,treeModalItem } = this.state;
    const { searchValue, expandedKeys, autoExpandParent,treeData } = this.state;
    const { buttonVisible } = this.state;
    // 成员弹窗框
    const modalProps = {
      handleCommit:this.handleCommit,
      handleModalVisible: this.handleModalVisible,
      modalItem,
      modalType,
      modalVisible,
    };
    // 节点弹出框
    const treeModalProps = {
      handleCommit: this.handleTreeCommit,
      handleModalVisible: this.handleTreeModalVisible,
      modalItem:treeModalItem,
      modalType:treeModalType,
      modalVisible:treeModalVisible,
    };

    const loop = data => data.map((item) => {
      // 裁剪包含searchValue的字符，高亮显示
      const index = item.title.indexOf(searchValue);
      const beforeStr = item.title.substr(0, index);
      const afterStr = item.title.substr(index + searchValue.length);
      const title = index > -1 ? (
        <span>
          {beforeStr}
          <span style={{ color: '#f50' }}>{searchValue}</span>
          {afterStr}
        </span>
      ) : <span>{item.title}</span>;
      if (item.children&&item.children.length) {
        return <TreeNode key={item.key} title={title} >{loop(item.children)}</TreeNode>
      }
      return <TreeNode key={item.key} title={title} />;
    });

    return (
      <PageHeaderLayout title="部门管理">
        <Row gutter={16}>
          <Col span={8}>
            <Card
              title="部门树"
              extra={
                <Button icon="plus" type="primary" onClick={() => this.handleTreeToModal({},'新增一级节点')}>
                  新增一级节点
                </Button>
              }
            >
              {buttonVisible&&
                (
                  <div>
                    <Button type="primary" size="small" onClick={()=>this.handleTreeToModal(treeModalItem,'新增下级部门')}>新增下级部门</Button>
                    <Divider type="vertical" />
                    <Button type="primary" size="small" onClick={()=>this.handleTreeToModal(treeModalItem,'修改本部门')}>修改本部门</Button>
                    <Divider type="vertical" />
                    <Button type="danger" size="small" onClick={this.handleTreeToDel}>删除本部门</Button>
                    <Divider />
                  </div>
                )
              }
              <Search style={{ marginBottom: 8 }} placeholder="Search" onChange={this.onChange} />
              <Row gutter={16} type="flex" align="middle">
                <Col span={16}>
                  <Tree
                    // showLine
                    onExpand={this.onExpand}
                    expandedKeys={expandedKeys}
                    autoExpandParent={autoExpandParent}
                    onSelect={this.handleTreeClick}
                    onRightClick={this.handleRightClick}
                    draggable
                    onDrop={this.onDrop}
                  >
                    {loop(treeData)}
                  </Tree>
                </Col>
              </Row>
            </Card>
          </Col>
          <Col span={16}>
            <Card
              title="直属成员"
              extra={
                <Button icon="plus" type="primary" onClick={() => this.handleToModal({},'新增')}>
                  添加成员
                </Button>
              }
            >
              <div className={styles.tableList}>
                <div className={styles.tableListOperator}>

                  {selectedRows.length > 0 && (
                    <span>
                      <Button>批量操作</Button>
                      <Dropdown>
                        <Button>
                          更多操作 <Icon type="down" />
                        </Button>
                      </Dropdown>
                    </span>
                  )}
                </div>
                <StandardTable
                  selectedRows={selectedRows}
                  loading={loading}
                  data={personData}
                  columns={columns}
                  onSelectRow={this.handleSelectRows}
                />
              </div>
            </Card>
          </Col>
        </Row>
        <CreateForm {...modalProps}  />
        <TreeForm {...treeModalProps}  />
      </PageHeaderLayout>
    );
  }
}
